package com.kgc.dao.mapper.user;

import com.kgc.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

/**
 * @author hyj
 * @time 2024/3/30 12:12
 * @describe
 */

public interface UserMapper {
    /**
     * 判断该用户名是否已注册
     *
     * @param username 用户名
     * @return null:not_exist User:exist
     */
    @Select("select user_id from users where username=#{username}")
    Integer selectByUsername(String username);

    /**
     * 判断该邮箱是否已注册
     *
     * @param email 邮箱
     * @return null:not_exist User:exist
     */
    @Select("select user_id from users where email=#{email}")
    Integer selectByEmail(String email);

    /**
     * 注册
     *
     * @param user 实体类
     * @return 1:success 0:fail
     */
    @Insert("insert into users(username, password, email, image, created_at, status, integral) value(#{username},#{password},#{email},#{image},#{createdAt},#{status},#{integral})")
    Integer registerUser(User user);

    /**
     * 注册时插入初始角色id
     *
     * @param email 根据邮箱查询用户id
     * @return 1:success 0:fail
     */
    @Insert("insert into user_roles(user_id, role_id) select user_id,1 from users where email = #{email}")
    Integer insertUserRoles(String email);

    /**
     * 登录 _ 判断是否为密码错误
     *
     * @param username 用户名/邮箱
     * @param password 密码
     * @return null:not_exist User:exist
     */
    @Select("select u.user_id from users u natural join user_roles ur where (username=#{username} and password=#{password}) or (email=#{username} and password=#{password})")
    Integer[] selectByEmailAndUsername(@Param("username") String username, @Param("password") String password);

    /**
     * 登录 _ 判断是否为权限不对等
     *
     * @param username 用户名/邮箱
     * @param password 密码
     * @return null:not_exist User:exist
     */
    @Select("select u.* from users u natural join user_roles ur where (role_id in (1,2,3) and username=#{username} and password=#{password}) or (role_id in (1,2,3) and email=#{username} and password=#{password})")
    User selectByEmailAndUsernameAndRoleId(@Param("username") String username, @Param("password") String password);

    /**
     * 更新用户密码
     *
     * @param email    邮箱
     * @param password 密码
     * @return 1:success 0:fail
     */
    @Update("update users set password=#{password} where email=#{email}")
    Integer updateUser(@Param("email") String email, @Param("password") String password);

    /**
     * 查找用户状态
     *
     * @param username 用户名
     * @return 1:正常 0:禁用
     */
    @Select("select status from users where username=#{username} or email=#{username}")
    Integer selectStatus(String username);
}
